<template>
  <file-list 
    ref="fileList"
    dir-path="threejs" 
    placeholder="请选择要查看的threejs示例"
    @before-load="handleBeforeLoad" 
  />
</template>

<script>
import FileList from '@/components/FileList';

export default {
  components: {
    FileList
  },

  data() {
    return {
      loadedScripts: new Set()
    };
  },

  mounted() {
    // 预加载 Threejs
    this.loadArcGISAPI();
  },

  methods: {
    loadExternalScript(src, type = 'js') {
      if (this.loadedScripts.has(src)) {
        return Promise.resolve();
      }

      return new Promise((resolve, reject) => {
        if (type === 'css') {
          const link = document.createElement('link');
          link.rel = 'stylesheet';
          link.href = src;
          link.onload = () => {
            this.loadedScripts.add(src);
            resolve();
          };
          link.onerror = reject;
          document.head.appendChild(link);
        } else {
          const script = document.createElement('script');
          script.src = src;
          script.onload = () => {
            this.loadedScripts.add(src);
            resolve();
          };
          script.onerror = reject;
          document.body.appendChild(script);
        }
      });
    },

    async loadArcGISAPI() {
      try {
        // 加载 Threejs CSS
        // await this.loadExternalScript('https://js.arcgis.com/4.26/esri/themes/light/main.css', 'css');
        // 加载 Threejs
        // <!-- 引入Three.js库 -->
      //   await this.loadExternalScript('https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js');
      //   //<!-- 引入OrbitControls控制器 -->
      //   await this.loadExternalScript('https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js');
      //   //<!-- 引入GLTFLoader加载器 -->
      //   await this.loadExternalScript('https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/loaders/GLTFLoader.js');
      //   //<!-- 引入状态监控器 -->
      //   await this.loadExternalScript('https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/libs/stats.min.js');
      //   //<!-- 引入RGBELoader加载HDR -->
      //   await this.loadExternalScript('https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/loaders/RGBELoader.js');
      //   //<!-- 引入拾取辅助工具 -->
      //   await this.loadExternalScript('https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/interactive/SelectionHelper.js');
      } catch (error) {
        console.error('加载 Threejs 失败:', error);
      }
    },

    async handleBeforeLoad(file) {

      // 确保 Threejs 已加载
      await this.loadArcGISAPI();
      // 等待 require 函数可用
      await new Promise((resolve) => {
        const checkRequire = setInterval(() => {
          if (window.require) {
            clearInterval(checkRequire);
            resolve();
          }
        }, 100);
      });
    }
  }
};
</script>